package com.gateway.common.holder;

import com.gateway.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Huangkai
 */
@Slf4j
public class RequestHolder {

    public static HttpServletRequest getRequest(){
        /**
         * 获取请求的request
         * */
        log.debug("get Request --- Thread id: {}, Thread name:{}",Thread.currentThread(),Thread.currentThread().getName());
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(servletRequestAttributes == null){
            return null;
        }
        return servletRequestAttributes.getRequest();
    }
    /**
     * 获取响应的response
     * */
    public static HttpServletResponse getResponse(){
        log.debug("get Request --- Thread id: {}, Thread name:{}",Thread.currentThread(),Thread.currentThread().getName());
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(servletRequestAttributes == null){
            return null;
        }
        return servletRequestAttributes.getResponse();
    }
    /**
     * 获取会话session
     * */
    public static HttpSession getSession(){
        log.debug("get Request --- Thread id: {}, Thread name:{}",Thread.currentThread(),Thread.currentThread().getName());
        HttpServletRequest httpServletRequest =null;
        if((httpServletRequest = getRequest())==null){
            return null;
        }
        return httpServletRequest.getSession();
    }
    /**
     *获取所有的session key
     * */
    public static String[] getSessionKeys(){
        log.debug("get Request --- Thread id: {}, Thread name:{}",Thread.currentThread(),Thread.currentThread().getName());
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null == servletRequestAttributes){
            return null;
        }
        return servletRequestAttributes.getAttributeNames(RequestAttributes.SCOPE_SESSION);
    }
}
